<template>
    <view>
        <view class="choose padding-md">
            <uv-checkbox-group v-model="selectedOptions">
                <view class="-margin-xs">
                    <uv-grid :col="2" :border="false">
                        <uv-grid-item v-for="(item, index) in list" :key="index" @click="onChooseItem(item)">
                            <view class="choose-item padding-xs">
                                <view class="bg-white padding-md border-radius-md">
                                    <view> <text>{{ item.title }}</text></view>
                                    <view>
                                        <text class="unit font-size-xs text-color-placeholder">{{ item.init_num }}{{
                                            item.unit
                                        }}</text>
                                    </view>
                                </view>
                                <view class="padding-md choose-item-checkbox">
                                    <uv-checkbox :name="item.id"></uv-checkbox>
                                </view>
                            </view>
                        </uv-grid-item>
                    </uv-grid>
                </view>
            </uv-checkbox-group>
        </view>
        <fixed-button buttonText="下一步" @on-tap="toPage"></fixed-button>
    </view>
</template>

<script lang="ts" setup>
import { queryThingOptions } from '@/api';
import { ref } from 'vue';
import { onShow, onPullDownRefresh } from '@dcloudio/uni-app';
import type { ThingOption } from './type';

var list = ref<ThingOption[]>([]);

var selectedOptions = ref<number[]>([]);

onPullDownRefresh(() => {
    getOptions();
    uni.stopPullDownRefresh
})

onShow(() => {
    getOptions();
})

function onChooseItem(row: ThingOption) {
    if (selectedOptions.value.includes(row.id)) {
        selectedOptions.value = selectedOptions.value.filter((item: number) => item !== row.id);
    } else {
        selectedOptions.value.push(row.id);
    }
}

function toPage() {
    const ids = selectedOptions.value;

    if (ids.length === 0) {
        uni.showToast({
            title: '请选择事件',
            icon: 'none'
        });
        return;
    }

    var selectedList = list.value.filter((item: ThingOption) => ids.includes(item.id));

    uni.navigateTo({
        url: '/pages/thing/create?rows=' + JSON.stringify(selectedList)
    });
}

async function getOptions() {
    try {
        const result: any = await queryThingOptions();
        list.value = result.data;
        return result;
    } catch (error) {
        return error;
    }
}
</script>

<style lang="scss" scoped>
.choose {
    &-item {
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        position: relative;

        &-checkbox {
            position: absolute;
            top: 0;
            right: -10rpx;
        }
    }
}
</style>